﻿/*
 *  GUI_Button.h
 *
 *	Date: 2011-12-5
 *  Author: linshenqi
 */
 
#include "./GUI.h"
#include <list>

using namespace std;

BEGIN_EVENT_TABLE(GUI_Button, wxWindow)
	EVT_PAINT(GUI_Button::OnPaint)
	EVT_MOUSE_EVENTS(GUI_Button::OnMouseEvent)
END_EVENT_TABLE()

GUI_Button::GUI_Button(wxWindow *pParent, int nID)
{
	m_pParent = pParent;
	this->SetTransparent(0);
	this->SetSize(wxSize(106, 32));
	this->SetWindowStyle(wxBORDER_NONE);
	this->ClearBackground();
	this->SetBackgroundStyle(wxBG_STYLE_CUSTOM);
	this->Create(m_pParent, nID);
	m_Size = this->GetSize();
	
	::wxInitAllImageHandlers();
	m_pBMP[BMP_UP] = new wxBitmap;
	m_pBMP[BMP_DOWN] = new wxBitmap;
	m_pBMP[BMP_OVER] = new wxBitmap;
	SetBMP(BMP_PATH_UP, BMP_PATH_DOWN, BMP_PATH_OVER);
	this->m_fX = double(double(m_Size.GetWidth()) / double(m_pBMP[BMP_UP]->GetWidth()));
	this->m_fY = double(double(m_Size.GetHeight()) / double(m_pBMP[BMP_UP]->GetHeight()));
	
	m_pBuffer = new wxBitmap;
	*m_pBuffer = *m_pBMP[BMP_UP];
	m_pDstDC = new wxClientDC(this);
	m_pDstDC->Clear();
	m_pDstDC->SetUserScale(m_fX, m_fY);
	m_pBufferDC = new wxMemoryDC;
	m_pMemDC = new wxMemoryDC;
}

GUI_Button::~GUI_Button()
{}

void GUI_Button::OnMouseEvent(wxMouseEvent& evt)
{
	bool bFlag = false;
	bool bRender = false;
	if(evt.LeftDown())
	{
		*m_pBuffer = *m_pBMP[BMP_DOWN];
		bRender = true;
	}
	else if(evt.LeftUp())
	{
		*m_pBuffer = *m_pBMP[BMP_OVER];
		bFlag = true;
		bRender = true;
	}
	else if(evt.Leaving())
	{
		*m_pBuffer = *m_pBMP[BMP_UP];
		bRender = true;
	}
	else if(evt.Entering())
	{
		*m_pBuffer = *m_pBMP[BMP_OVER];
		bRender = true;
	}
	
	if(bRender)
		Render();
	
	if(bFlag)
	{
		wxCommandEvent ce(wxEVT_COMMAND_BUTTON_CLICKED, this->GetId());
		this->Command(ce);
	}
}

#define DT	wxCOPY
void GUI_Button::Render(wxDC *pDC)
{
	if(!pDC)
		pDC = m_pDstDC;
		
	m_pBufferDC->SelectObject(*m_pBuffer);
	
	pDC->Clear();
	pDC->SetUserScale(m_fX, m_fY);
	pDC->Blit(0, 0, m_pBuffer->GetWidth(), m_pBuffer->GetHeight(), m_pBufferDC, 0, 0, DT, true);
	
	m_pBufferDC->SelectObject(wxNullBitmap);
}

void GUI_Button::SetBMP(const wxString& sUp, const wxString& sDown, const wxString& sOver)
{
	m_pBMP[BMP_UP]->LoadFile(sUp, wxBITMAP_TYPE_PNG);
	m_pBMP[BMP_DOWN]->LoadFile(sDown, wxBITMAP_TYPE_PNG);
	m_pBMP[BMP_OVER]->LoadFile(sOver, wxBITMAP_TYPE_PNG);
}

void GUI_Button::OnPaint(wxPaintEvent& evt)
{
	wxPaintDC dc(this);
	
	Render(&dc);
}